# coding = utf-8

'''
灰度直方图的绘制
'''

import os
import numpy as np
import pydicom
import matplotlib.pyplot as plt

import os
import pydicom
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from medpy.io import load, save
import SimpleITK as sitk

def read_data():
    root = "/datasets/qiye/image_venous"
    file_list = sorted(os.listdir(root))

    label_root = "/datasets/qiye/liver"
    label_file_list = sorted(os.listdir(label_root))

    tumor_root = "/datasets/qiye/lesion"
    tumor_file_list = sorted(os.listdir(tumor_root))

    for i in range(35, 46):
        file_name = os.path.join(root, file_list[i])
        data = sitk.GetArrayFromImage(sitk.ReadImage(file_name))

        mask_file = os.path.join(label_root, label_file_list[i])
        mask = sitk.GetArrayFromImage(sitk.ReadImage(mask_file))

        tumor_file = os.path.join(tumor_root, tumor_file_list[i])
        tumor = sitk.GetArrayFromImage(sitk.ReadImage(tumor_file))

        his_data = []
        tumor_data = []
        for a in range(mask.shape[0]):
            for b in range(mask.shape[1]):
                for c in range(mask.shape[2]):
                    if mask[a][b][c] == 0:
                        continue
                    if data[a][b][c] >250 or data[a][b][c] < -250:
                        continue
                    if tumor[a][b][c] == 1:
                         tumor_data.append(data[a][b][c])
                    else:
                        his_data.append(data[a][b][c])

        liver = np.array(his_data)
        tumor = np.array(tumor_data)

        fig, ax1 = plt.subplots()
        ax2 = ax1.twinx()
        ax1.hist([liver, tumor], bins=100, color=['b', 'r'])
        n, bins, patches = ax1.hist([liver, tumor], bins=100)
        ax1.cla()  # clear the axis

        width = (bins[1] - bins[0]) * 0.4
        bins_shifted = bins + width
        ax1.bar(bins[:-1], n[0], width, align='edge', color='b')
        ax2.bar(bins_shifted[:-1], n[1], width, align='edge', color='r')

        colors = ['b', 'r']

        ax1.set_ylabel("liver hu Count", color=colors[0])
        ax2.set_ylabel("tumor hu Count", color=colors[1])
        ax1.tick_params('y', colors=colors[0])
        ax2.tick_params('y', colors=colors[1])
        plt.tight_layout()
        plt.title("total")

        plt.show()

if __name__ == '__main__':
    read_data()